package com.bot.edu.applysystem.audition.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bot.edu.applysystem.audition.entity.vo.CourseVo;
import com.bot.edu.applysystem.audition.entity.vo.MajorCourseVo;
import com.bot.edu.informationmanage.course.entity.Course;
import com.bot.edu.informationmanage.course.service.ICourseService;
import com.bot.edu.informationmanage.major.entity.Major;
import com.bot.edu.informationmanage.major.service.IMajorService;
import com.bot.edu.noticessystem.notices.entity.Notices;
import com.bot.edu.noticessystem.notices.service.INoticesService;
import com.bot.edu.utils.SnowFlake;
import com.bot.edu.utils.ToNotices;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import com.bot.edu.applysystem.audition.entity.AuditionApplication;
import com.bot.edu.applysystem.audition.service.IAuditionApplicationService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 试听申请表
 * @Author: jeecg-boot
 * @Date:   2022-04-21
 * @Version: V1.0
 */
@Api(tags="试听申请表")
@RestController
@RequestMapping("/audition/auditionApplication")
@Slf4j
public class AuditionApplicationController extends JeecgController<AuditionApplication, IAuditionApplicationService> {
	@Autowired
	private IAuditionApplicationService auditionApplicationService;

	 @Autowired
	 private ICourseService courseService;

	 @Autowired
	 private IMajorService majorService;

	 @Autowired
     private INoticesService noticesService;
	
	/**
	 * 分页列表查询
	 *
	 * @param auditionApplication
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "试听申请表-分页列表查询")
	@ApiOperation(value="试听申请表-分页列表查询", notes="试听申请表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<AuditionApplication>> queryPageList(AuditionApplication auditionApplication,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<AuditionApplication> queryWrapper = QueryGenerator.initQueryWrapper(auditionApplication, req.getParameterMap());
		Page<AuditionApplication> page = new Page<AuditionApplication>(pageNo, pageSize);
		IPage<AuditionApplication> pageList = auditionApplicationService.page(page, queryWrapper);


		//展示课程
		List<Course> courseList = courseService.list();
		List<AuditionApplication> pageRecords = pageList.getRecords();
		for (AuditionApplication pageRecord : pageRecords) {

			String courseStr = "";

			String pageRecordCourseId = pageRecord.getCourseId();
			String[] courseIds = pageRecordCourseId.split(",");


			for (String courseId : courseIds) {
				for (Course course : courseList) {
					if (courseId.equals(course.getCourseId())){
						courseStr=course.getCourseName();
					}
				}
			}

			pageRecord.setCourseId(courseStr);

		}


		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param auditionApplication
	 * @return
	 */
	@AutoLog(value = "试听申请表-添加")
	@ApiOperation(value="试听申请表-添加", notes="试听申请表-添加")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody AuditionApplication auditionApplication) {
		//雪花算法生成试听申请编号
		String application_id = SnowFlake.getId();
		auditionApplication.setApplicationId(application_id);

		auditionApplicationService.save(auditionApplication);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param auditionApplication
	 * @return
	 */
	@AutoLog(value = "试听申请表-编辑")
	@ApiOperation(value="试听申请表-编辑", notes="试听申请表-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody AuditionApplication auditionApplication) {
		auditionApplicationService.updateById(auditionApplication);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "试听申请表-通过id删除")
	@ApiOperation(value="试听申请表-通过id删除", notes="试听申请表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		auditionApplicationService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "试听申请表-批量删除")
	@ApiOperation(value="试听申请表-批量删除", notes="试听申请表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.auditionApplicationService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	 /**
	  *  批量修改状态（通过）
	  *
	  * @param ids
	  * @return
	  */
	 @AutoLog(value = "试听申请表-批量通过")
	 @ApiOperation(value="试听申请表-批量通过", notes="试听申请表-批量通过")
	 @RequestMapping(value = "/updateStatusYBatch")
	 public Result<String> updateStatusYBatch(@RequestParam(name="ids",required=true) String ids) {
		 UpdateWrapper<AuditionApplication> updateWrapper = new UpdateWrapper<>();
		 updateWrapper.lambda()
				 .in(AuditionApplication::getId, Arrays.asList(ids.split(",")))
				 .set(AuditionApplication::getApplicationStatus,1);
		 this.auditionApplicationService.update(updateWrapper);
         Notices notices = ToNotices.toNotices( "您的预约已处理，请在我的预约中查看");
         noticesService.save(notices);
		 return Result.OK("批量通过成功!");
	 }
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "试听申请表-通过id查询")
	@ApiOperation(value="试听申请表-通过id查询", notes="试听申请表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<AuditionApplication> queryById(@RequestParam(name="id",required=true) String id) {
		AuditionApplication auditionApplication = auditionApplicationService.getById(id);
		if(auditionApplication==null) {
			return Result.error("未找到对应数据",null);
		}
		return Result.OK(auditionApplication);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param auditionApplication
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AuditionApplication auditionApplication) {
        return super.exportXls(request, auditionApplication, AuditionApplication.class, "试听申请表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, AuditionApplication.class);
    }

	 /**
	  *
	  * C端试听  专业 -- 课程联动选择器
	  *
	  *
	  * @return
	  **/
	 @RequestMapping(value = "/showMajorCourse", method = RequestMethod.GET)
	 public Result<?> showMajorCourse(){


		 ArrayList<MajorCourseVo> majorCourseList = new ArrayList<>();

		 QueryWrapper<Major> majorQueryWrapper = new QueryWrapper<>();
		 majorQueryWrapper.select("major_id","major_name");

		 List<Major> list = majorService.list(majorQueryWrapper);

		 for (Major major : list) {
			 MajorCourseVo majorCourseVo = new MajorCourseVo();
			 majorCourseVo.setMajorId(major.getMajorId());
			 majorCourseVo.setMajorName(major.getMajorName());
			 majorCourseList.add(majorCourseVo);
		 }

		 for (MajorCourseVo majorCourseVo : majorCourseList) {
			 QueryWrapper<CourseVo> courseVoQueryWrapper = new QueryWrapper<>();
			 courseVoQueryWrapper.eq("major_id",majorCourseVo.getMajorId());
			 List<CourseVo> courseVoList = courseService.getCourseByMajorId(courseVoQueryWrapper);
			 majorCourseVo.setCourses(courseVoList);
		 }



		 return Result.ok(majorCourseList);
	 }

	 /**
	  * C端 立即预约  预约线下试听
	  *
	  * @param
	  * @param
	  * @return
	  */
	 @RequestMapping(value = "/nowSubcribe", method = RequestMethod.POST)
	 public Result<?> nowSubcribe(@RequestBody AuditionApplication auditionApplication) {
		 //雪花算法生成试听申请编号
		 String application_id = SnowFlake.getId();
		 auditionApplication.setApplicationId(application_id);

		 auditionApplicationService.save(auditionApplication);
		 return Result.ok("添加成功！");
	 }

	 /**
	  * C端 我的试听预约查看
	  *
	  * @param
	  * @param
	  * @return
	  */
	 @RequestMapping(value = "/showAuditionApplicationByUserId", method = RequestMethod.POST)
	 public Result<?> showAuditionApplicationByUserId(
			 @RequestParam(name="userId") String userId,
			 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
			 @RequestParam(name="pageSize", defaultValue="5") Integer pageSize
	          ) {

		 QueryWrapper<AuditionApplication> auditionApplicationQueryWrapper = new QueryWrapper<>();
		 auditionApplicationQueryWrapper.lambda().eq(AuditionApplication::getUserId,userId);

		 Page<AuditionApplication> page = new Page<AuditionApplication>(pageNo, pageSize);
		 IPage<AuditionApplication> pageList = auditionApplicationService.page(page, auditionApplicationQueryWrapper);



		 //展示课程
		 List<Course> courseList = courseService.list();
		 List<AuditionApplication> pageRecords = pageList.getRecords();
		 for (AuditionApplication pageRecord : pageRecords) {

			 String courseStr = "";

			 String pageRecordCourseId = pageRecord.getCourseId();
			 String[] courseIds = pageRecordCourseId.split(",");


			 for (String courseId : courseIds) {
				 for (Course course : courseList) {
					 if (courseId.equals(course.getCourseId())){
						 courseStr=course.getCourseName();
					 }
				 }
			 }

			 pageRecord.setCourseId(courseStr);

		 }


		 return Result.ok(pageList);
	 }

	 @GetMapping("/getCourseCount")
     public Result<?> getCourseCount(String userId){
         QueryWrapper<AuditionApplication> auditionApplicationQueryWrapper = new QueryWrapper<>();
         auditionApplicationQueryWrapper.lambda().eq(AuditionApplication::getUserId,userId);
         int count = auditionApplicationService.count(auditionApplicationQueryWrapper);
         return Result.ok(count);
     }

}
